/**
 * 
 * File: PagerFilter.java
 *   
 * Copyright (C): 2009
 *
 * Description:
 * <<该过滤器负责设置分页参数>>
 *
 *
 * Revision History:
 * <<Date>>, <<Who>>, <<What>> 
 */
package com.yypx.common.navigation;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Zz
 * @since 2009-09-03
 * @version 1.0
 */

public class PagerFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		SystemContext.setOffset(this.getOffset(req));
		SystemContext.setPagesize(this.getPagesize(req));
		SystemContext.setMaxIndexPages(this.getMaxIndexPages(req));
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			chain.doFilter(request, response);
		} catch (Exception e) {

		} finally {
			SystemContext.removeOffset();
			SystemContext.removePagesize();
			SystemContext.removeMaxIndexPages();
		}
	}

	/**
	 * 获取分页起点
	 * @param request
	 * @return
	 */
	protected int getOffset(HttpServletRequest request) {
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
			if(offset<=0)
				offset = 0;
		} catch (NumberFormatException e) {
//			System.out.println("--------------------");
			
		}
		return offset;
	}

	/**
	 * 获取分页数
	 * @param request
	 * @return
	 */
	protected int getPagesize(HttpServletRequest request) {
		int pagesize = 10;
		try {
			pagesize = Integer.parseInt(request
					.getParameter("pager.maxPageItems"));
			if(pagesize<=0)
				pagesize = 10;
		} catch (NumberFormatException e) {
//			System.out.println("--------------------");
			// e.printStackTrace();
		}
		return pagesize;
	}

	protected int getMaxIndexPages(HttpServletRequest request) {
		int maxIndexPages = 5;
		try {
			maxIndexPages = Integer.parseInt(request
					.getParameter("pager.maxIndexPages"));
			if(maxIndexPages<=0)
				maxIndexPages = 5;
		} catch (NumberFormatException e) {
//			System.out.println("--------------------");
			// e.printStackTrace();
		}
		return maxIndexPages;
	}

	public void init(FilterConfig arg0) throws ServletException {
	}
}
